React = require('react')
# Card = require('antd-mobile/lib/card')
# Flex = require('antd-mobile/lib/flex')
# Icon = require('antd-mobile/lib/icon')
Toast = require('antd-mobile/lib/toast')

RefreshControl = require('antd-mobile/lib/refresh-control')
TimerMixin = require('react-timer-mixin')
{View,TouchableNativeFeedback,InteractionManager,Image,Text,ScrollView,ListView,TouchableHighlight,StyleSheet,Navigator,TouchableOpacity,ActivityIndicator} = require('react-native')
# ListView = require('antd-mobile/lib/list-view')

Dimensions = require('Dimensions')
{IndexedList} = ListView
{ width, height } = Dimensions.get('window')
{View} = require('react-native')
{fetchGetList,fetchRefreshList} = require('../actions/page_bwss.js')
{connect} = require('react-redux')
moment = require('moment')
_ = require('underscore')

backImg = require('../img/back.png')
searchIcon = require('../img/search_white.png')
# basePage = require('../mixins/basePage.js')
Page_bwss_detail = require('./page_bwss_detail.js')
Page_Bwss = React.createClass
  mixins:[TimerMixin]
  getInitialState:->
    @ds = new ListView.DataSource
      rowHasChanged:(r1,r2)->r1 isnt r2
      sectionHeaderHasChanged:(s1,s2)->s1 isnt s2
      getSectionHeaderData:(dataBlob,sectionID)->
        dataBlob[sectionID]
      getRowData:(dataBlob,sectionID,rowID)->
        dataBlob[sectionID][rowID]
    @sectionPosition = {}
    # @gqState = 0
    {
      isFirstLoad:true
      selectSection:null
    }
  _processTime:(time)->
    t = moment(time)
    t.format('DD/hhmm')
  refreshList:->
    @setState selectSection:null
    @props.fetchRefresh()
  componentDidMount:->
    drt = moment.duration(2, 'days')
    @lazyLoad(drt)
    # @initFetchData()
  componentDidUpdate:->
    if @state.selectSection
      @refs.listView.scrollTo {x:0,y:0,animated:true}
  initFetchData:->
    debugger
    that = @
    if @props.connected
      setTimeout ->
        that.props.fetchRefresh()
        that.setState isFirstLoad:false
      ,600
    else
      @setState
        isFirstLoad:false
  lazyLoad:(duration)->
    InteractionManager.runAfterInteractions =>
      if @props.connected
        if @props.lastFetchTime
          lastTime = moment(@props.lastFetchTime)
          currTime = moment(new Date())
          if currTime.subtract(duration).isAfter(lastTime)
            @props.fetchRefresh()
        else
          @props.fetchRefresh()
      @setState isFirstLoad:false
  delayLoad:(duration)->
    debugger
    setTimeout =>
      debugger
      if @props.lastFetchTime
        lastTime = moment(@props.lastFetchTime)
        currTime = moment(new Date())
        if currTime.subtract(duration).isAfter(lastTime)
          @props.fetchRefresh()
      else
        @props.fetchRefresh()
      @setState
        isFirstLoad:false
    ,800

  _renderBody:->
    debugger
    if @state.isFirstLoad
      <View style={width:width,height:height,backgroundColor:'#ffffff'}/>
    else
      @_renderListView()
  _renderListHeader:->
    if @props.connected is false and @props.list.length>0
      <TopNotice mode="closable" style={{margin:10}}>
        无网络连接，您现在看到的是离线缓存数据
      </TopNotice>
  _renderListFooter:->
    debugger
    listView = @refs.listView
    dataSource = @dataSource
    count = dataSource.getRowCount()
    curRenderedRowsCount = listView?.state.curRenderedRowsCount
    if @props.completed and curRenderedRowsCount>0 and curRenderedRowsCount is count
      <View style={{flexDirection:'row',justifyContent:'center',paddingTop:20,paddingBottom:30}}>
        <Text>到底了</Text>
      </View>
    else unless @props.refreshing
      <View style={{flexDirection:'row',justifyContent:'center',paddingTop:20,paddingBottom:30}}>
        <ActivityIndicator size='small'></ActivityIndicator>
        <Text style={{marginLeft:5}}>正在加载</Text>
      </View>
    else
      <View/>
      # <View style={{flexDirection:'row',justifyContent:'center',paddingBottom:20}}>
      #   <ActivityIndicator size='small'></ActivityIndicator>
      #   <Text>正在加载</Text>
      # </View>
  _renderListSeparator:(sectionID,rowID)->
    <View key={"separator_#{sectionID}#{rowID}"} style={{height:1,backgroundColor:'#CCCCCC'}}/>
  _renderSectionHeader:(sectionData, sectionID)->
    debugger
    that = @
    <View key={"section_#{sectionID}"}>
      <Text>{sectionID}</Text>
    </View>
    # <View key={"section_#{sectionID}"} onLayout={(e)->
    #     debugger
    #     layout = e.nativeEvent.layout
    #     that.sectionPosition[sectionID] = layout
    #   }>
    #   <Text>{sectionID}</Text>
    # </View>
  _renderListView:->
    <ListView ref='listView' dataSource={@dataSource} style={{flex:1}}
          renderHeader={@_renderListHeader}
          renderSectionHeader={@_renderSectionHeader}
          renderRow={@_renderRow}
          renderSeparator={this._renderListSeparator}
          renderFooter={@_renderListFooter}
          initialListSize={5}
          pageSize={5}
          scrollRenderAheadDistance={60}
          refreshControl={
            <RefreshControl refreshing={@props.refreshing} onRefresh={@refreshList}
                distanceToRefresh={60}
                resistance={2.5}
                hammerOptions={{
                  touchAction:'auto'
                  recognizers:
                    pan:
                      threshold:10
                  }}/>
          }>
    </ListView>
    # stickyProps={{
    #   stickyStyle: { zIndex: 999, top: 43 },
    #   topOffset: -43,
    # }}
    # quickSearchBarStyle={{
    #   position:'absolute'
    #   top:85
    #   }}

  _renderHeader:->
      <View style={{flexDirection:'row',flex:0,height:60,alignItems:'center', justifyContent:'center',backgroundColor:'#0066FF'}}>
        <View style={{flex:1,padding:10}}>
          <TouchableOpacity onPress={=>@props.navigator.pop()}>
            <Image source={backImg}  style={{height:30,width:30,resizeMode:'contain'}}/>
          </TouchableOpacity>
        </View>
        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
          <Text style={{fontSize:20,color:'#ffffff'}}>泊位水深</Text>
        </View>

        <View style={{flex:1,alignItems:'flex-end',padding:10}}>
          <TouchableOpacity onPress={@_showActionSheet}>
          </TouchableOpacity>
        </View>
      </View>
  rowClick:(model)->
    {navigator} = @props
    setTimeout ->
      navigator.push
        component:Page_bwss_detail
        name:'Page_bwss_detail'
        title:'详情'
        params:
          model:model
    ,200
  _renderRow:(rowData,sectionID,rowID,highlightRow)->
    # @highlightRow = highlightRow
    <TouchableHighlight key={rowID} onPress={@rowClick.bind(@,rowData)} >
      <View style={{flexDirection:'column'}}>
        <View style={{flexDirection:'row',padding:5, backgroundColor:'#ffffff',justifyContent:'center',alignItems:'center'}}>
          <View style={{flex:3}}>
            <Text>{rowData.VCPLACESNAME}</Text>
          </View>
        </View>
        <View style={{flexDirection:'row',padding:5, backgroundColor:'#ffffff',justifyContent:'center',alignItems:'center'}}>
          <View style={{flex:1}}>
            <Text>{"港区:#{rowData.GQNAME}"}</Text>
          </View>
          <View style={{flex:1}}>
            <Text>{"所属码头:#{rowData.MTNAME}"}</Text>
          </View>
        </View>
        <View style={{flexDirection:'row',padding:5, backgroundColor:'#ffffff',justifyContent:'center',alignItems:'center'}}>
          <View style={{flex:1}}>
            <Text>{"泊位性质:#{rowData.XZNAME}"}</Text>
          </View>
          <View style={{flex:1}}>
            <Text>{"泊位水深:#{rowData.NMWATERLEN}"}</Text>
          </View>
        </View>
        <View style={{flexDirection:'row',padding:5, backgroundColor:'#ffffff',justifyContent:'center',alignItems:'center'}}>
          <View style={{flex:1}}>
            <Text>{"水深更新时间:#{moment(rowData.DTWATERLENUPDATETIME).format('YYYY-MM-DD')}"}</Text>
          </View>
          <View style={{flex:1}}>
          </View>
        </View>
      </View>
    </TouchableHighlight>

  slideBarClickHandle:(sectionID)->
    this.setTimeout =>
      this.setState selectSection:sectionID
    ,600
    # InteractionManager.runAfterInteractions =>
    # 之前的方案，全部加载数据，滚动到相应位置（慢）
    # layout = @sectionPosition[sectionID]
    # if layout
    #   @refs.listView.scrollTo x:layout.x,y:layout.y,animate:true
  _renderSlideBar:(actions)->
      <View  style={{opacity:0.3,width:40,position:'absolute',top:70,right:0,bottom:10,zIndex:999}}>
        {
          for item in actions
            <View key={"slideBar_#{item}"} style={{flex:1,width:50,margin:0,padding:0,justifyContent:'center',alignItems:'center'}}>
              <TouchableHighlight  style={{width:50,flex:1,justifyContent:'center',alignItems:'center'}} onPress={@slideBarClickHandle.bind(@,item)}>
                <View style={{flexDirection:'column',flex:1,justifyContent:'center',alignItems:'center'}}>
                  <Text style={{flex:1,color:'#000000',fontSize:16}}>{item}</Text>
                </View>
              </TouchableHighlight>
            </View>
        }
      </View>
  render:->
    # debugger
    # return <View/>
    # @dataSource = @ds.cloneWithRows(@props.list)
    debugger
    sectionIDs = []
    rowIDs = []
    for own k,v of @props.list
      sectionIDs.push k
    sectionIDs = _.sortBy sectionIDs
    unless @state.selectSection
      index = 0
      for k in sectionIDs
        rowIDs[index] = []
        i = 0
        for l in @props.list[k]
          rowIDs[index].push i
          i++
        index++
      @dataSource = @ds.cloneWithRowsAndSections  @props.list,sectionIDs,rowIDs
    else
      filterList = {}
      filterList[@state.selectSection] = @props.list[@state.selectSection]
      filterRowIds = []
      index = 0
      filterRowIds[0] =
        for ite in filterList[@state.selectSection]
          index++
      @dataSource = @ds.cloneWithRowsAndSections  filterList,[@state.selectSection],filterRowIds

    <View style={width:width,height:height,flexDirection:'column',backgroundColor:'#ffffff',paddingBottom:10}>
      {@_renderHeader()}
      <View  style={{height:1,width:width,backgroundColor:'#CCCCCC'}}/>
      <View style={{flex:1}}>
        {@_renderBody()}
      </View>
      {@_renderSlideBar(sectionIDs)}
    </View>


styles = StyleSheet.create
  row:
    flexDirection:'column'
    justifyContent:'center'
    padding:5
    backgroundColor:'#F6F6F6'
  text:
    flex:1

mapStateToProps = (state)->
  list:state.page_bwss.list
  isLoading:state.page_bwss.isLoading
  pageIndex:state.page_bwss.pageIndex
  completed:state.page_bwss.completed
  refreshing:state.page_bwss.refreshing
  lastFetchTime:state.page_bwss.lastFetchTime
  connected:state.appState.connected
mapDispatchToProps = (dispatch,wonProps)->
  fetchGet:(pageNum)->
    dispatch fetchGetList(pageNum)
  fetchRefresh:->
    dispatch fetchRefreshList()

module.exports = connect(mapStateToProps,mapDispatchToProps)(Page_Bwss)
